// vite.main.config.mjs
import { defineConfig } from 'vite';
import { resolve } from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import commonjs from '@rollup/plugin-commonjs';
import nodeResolve from '@rollup/plugin-node-resolve';
import { nodePolyfills } from 'vite-plugin-node-polyfills';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const builtinModules = ['util', 'fs', 'path', 'stream', 'buffer'];

const isProduction = process.env.NODE_ENV === 'production';

export default defineConfig({
  mode: process.env.NODE_ENV || 'development',
  build: {
    outDir: resolve(__dirname, '.vite/build/main'),
    emptyOutDir: true,
    target: 'node18',
    
    lib: {
      entry: resolve(__dirname, 'src/main/main.js'),
      formats: ['es'],
      fileName: (format) => `main.${format}.js` // 更专业的动态命名
    },
    
    sourcemap: isProduction ? 'hidden' : 'inline',
    minify: isProduction ? 'terser' : false,
    
    rollupOptions: {
      external: [
        ...builtinModules,
        ...builtinModules.map(m => `node:${m}`),
        'electron',
        '@vue/runtime-dom',
        '@vue/devtools-api',
        '@vue/devtools-kit'
      ],
      
      plugins: [
        nodeResolve({
          preferBuiltins: true,
          exportConditions: ['node'],
          extensions: ['.js', '.node']
        }),
        
        commonjs({
          requireReturnsDefault: 'auto',
          esmExternals: true,
          transformMixedEsModules: true,
          include: [
            'node_modules/stubborn-fs/**',
            'node_modules/electron-squirrel-startup/**',
            'node_modules/electron-store/**'
          ]
        })
      ],
      
      output: {
        format: 'es',
        entryFileNames: '[name].js',
        chunkFileNames: '[name].js',
        inlineDynamicImports: true
      }
    }
  },

  plugins: [
    nodePolyfills({  // 添加 .default
      protocolImports: true,
      overrides: {
        util: 'node:util',
        fs: 'node:fs',
        path: 'node:path'
      }
    })
  ],

  resolve: {
    alias: {
      '@main': resolve(__dirname, 'src/main'),
      '@shared': resolve(__dirname, 'src/shared')
    },
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.node', '.vue']
  },

  define: {
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    'process.env.APP_VERSION': JSON.stringify(process.env.npm_package_version)
  },

  optimizeDeps: {
    disabled: true
  }
});